<template>
  <div class="shopcar-contain">
    <template v-if="goodsList?.length > 0">
      <div class="bigbox">
        <!-- 收货地址 -->
        <van-contact-card
          v-if="!shopStore.address.id"
          type="add"
          add-text="添加收货地址"
          @click="onAdd"
        />
        <div v-else>
          <div class="address" @click="onAdd">
            <div class="left">
              <van-icon name="logistics" />
              <div class="text">
                <div>
                  {{ newAddress.province }}{{ newAddress.city
                  }}{{ newAddress.country }}

                  <van-tag type="danger" v-if="newAddress.isDefault"
                    >默认</van-tag
                  >
                </div>
                <span class="particulars">{{ newAddress.addressDetail }}</span>
                <span>{{ newAddress.name }} {{ newAddress.tel }}</span>
              </div>
            </div>
            <van-icon name="arrow" />
          </div>
          <div class="line">
            <div
              v-for="i in 20"
              :key="i"
              :class="['item', 'bg' + (i % 2) + 1]"
            ></div>
          </div>
        </div>
        <!-- 商品 -->
        <div class="goods-list">
          <div
            class="goods"
            v-for="item in shopStore.shopCarList"
            :key="item.id"
          >
            <van-checkbox
              style="z-index: 9"
              checked-color="#ee0a24"
              v-model="item.isSelected"
              @change="changeSelected($event, item.id)"
            ></van-checkbox>
            <div class="box">
              <img :src="getGoods(item.id)?.thumb_path" />
              <div class="text">
                <div class="title">{{ getGoods(item.id)?.title }}</div>
                <div class="particulars">
                  <div class="price">￥{{ getGoods(item.id)?.sell_price }}</div>
                  <van-stepper
                    v-model="item.number"
                    @change="changeNumber($event, item.id)"
                  />
                  <van-button type="danger" @click="del(item.id)"
                    >删除</van-button
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <van-submit-bar
        tip="默认只支持微信支付"
        :price="shopStore.totalPrice * 100"
        button-text="去结算付款"
        @submit="onSubmit"
      >
        <template #default>共{{ shopStore.totalSelectedNum }}件商品</template>
      </van-submit-bar>
    </template>

    <div class="empty" v-else>
      <img src="../assets/images/car.png" alt="" />
      <div class="text1">购物车竟然是空的</div>
      <div class="text2">再忙，也要买点什么犒劳自己~</div>
      <van-button @click="$router.push('/home')">去首页逛逛</van-button>
    </div>
    <div class="login" v-if="!shopStore.token">
      <van-button type="danger" @click="$router.push('/login')"
        >立即登录</van-button
      >
    </div>
  </div>
</template>

<script setup>
import { getShopCarList, commitOrder } from "@/api/";
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
import { Toast } from "vant";
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
const $route = useRoute();
const $router = useRouter();
import useShopStore from "@/store/shop";
const shopStore = useShopStore();

const shopCarListId = ref([]);
const goodsList = ref([]);
const newAddress = shopStore.address;

// 提交订单
const onSubmit = async () => {
  // 判断是否有选中的商品
  if (!shopStore.totalNum) {
    Toast("请选择商品");
    return;
  }
  // 判断是否选中地址
  if (!newAddress.id) {
    Toast("请选择地址");
    return;
  }
  // 订单编号
  let randomNum = "";
  for (let i = 0; i < 5; i++) {
    randomNum += parseInt(Math.random() * 10);
  }
  let orderSerialNum =
    proxy.$momentFun(Date.now(), "YYYYMMDDHHmmss") + randomNum;
  // 选中的id
  // let selectedId = shopStore.shopCarList.map((item) => {
  //   if (item.isSelected) {
  //     return item.id;
  //   }
  // });
  let selectedId = [];
  shopStore.shopCarList.forEach((item) => {
    if (item.isSelected) {
      selectedId.push(item.id);
    }
  });

  //  生成订单信息
  let orderInfo = {
    order_id: orderSerialNum,
    address_id: newAddress.id,
    total_price: shopStore.totalPrice,
    number: shopStore.totalNum,
    goods_ids: selectedId.join(","),
  };
  // 发送请求
  let { code } = await commitOrder(orderInfo);
  if (code === 20000) {
    $router.push("/orderdetail/" + orderSerialNum);
  }

  // 留下未选中的商品
  // let shopCarList = shopStore.shopCarList.map((item) => {
  //   if (!item.isSelected) {
  //     return item;
  //   }
  // });
  // console.log(shopCarList);
  let shopCarList = [];
  shopStore.shopCarList.forEach((item) => {
    if (!item.isSelected) {
      shopCarList.push(item);
    }
  });

  shopStore.setShopCarList(shopCarList);
};

// 更改地址
const onAdd = () => {
  $router.push("/address?flag=true");
};
const getGoods = (id) => {
  return goodsList.value.find((item) => item.id == id);
};

// 更改是否选中
const changeSelected = (bool, id) => {
  let shopCarList = shopStore.shopCarList.map((item) => {
    if (item.id === id) {
      item.isSelected = bool;
    }
    return item;
  });
  shopStore.setShopCarList(shopCarList);
};

// 改变数量
const changeNumber = (value, id) => {
  let shopCarList = shopStore.shopCarList.map((item) => {
    if (item.id === id) {
      item.number = value;
    }
    return item;
  });
  shopStore.setShopCarList(shopCarList);
};

// 删除商品
const del = async (id) => {
  shopCarListId.value = shopCarListId.value.filter((item) => item !== id);

  let { message } = await getShopCarList(shopCarListId.value.join(","));
  goodsList.value = message;
  let shopCarList = shopStore.shopCarList.filter((item) => {
    return item.id !== id;
  });
  shopStore.setShopCarList(shopCarList);
};

onMounted(async () => {
  // 获取购物车商品列表
  shopCarListId.value = shopStore.shopCarList.map((item) => item.id);
  let { message } = await getShopCarList(shopCarListId.value.join(","));
  goodsList.value = message;
});
</script>
<script>
export default {
  beforeRouteEnter(to, from, next) {
    if (from.name === "particulars") {
      to.meta.isShowBackIcon = true;
    } else {
      to.meta.isShowBackIcon = false;
    }
    next();
  },
};
</script>

<style lang="scss" scoped>
.shopcar-contain {
  .empty {
    text-align: center;

    img {
      width: 110px;
      height: 110px;
      margin: 30px auto;
    }

    .text1 {
      margin-bottom: 15px;
      font-size: 18px;
      text-align: center;
    }

    .text2 {
      margin-bottom: 30px;
      font-size: 13px;
      text-align: center;
    }

    .van-button {
      background: transparent;
      border: 1px solid #ccc;
    }
  }

  .login {
    margin-top: 30px;
    text-align: center;

    .van-button {
      border-radius: 20px;
    }
  }

  .van-contact-card {
    margin-top: 5px;
  }

  .address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 5px 10px;
    margin-top: 5px;
    background: #fff;
    border-radius: 6px;

    .van-icon {
      color: #969799;
    }

    .left {
      display: flex;
      align-items: center;

      .van-icon {
        margin-right: 10px;
        color: red;
      }

      .text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        font-size: 14px;
        line-height: 20px;

        .particulars {
          font-size: 16px;
          font-weight: 700;
        }
      }
    }
  }

  ::v-deep(.line) {
    display: flex;
    justify-content: space-evenly;
    padding: 2px;
    background: #fff;

    .item {
      width: 14px;
      height: 5px;
      margin: 0;
      transform: skewX(-45deg);
    }

    .bg11 {
      background-color: rgb(12 171 234);
    }

    .bg01 {
      background-color: rgb(226 13 13);
    }
  }

  .goods-list {
    .goods {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 5px;
      margin: 5px 2px;
      background: #fff;
      border-radius: 6px;

      .box {
        display: flex;
        justify-content: space-between;
        padding: 10px;

        img {
          width: 82px;
          height: 100px;
        }

        .text {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          width: 206px;
          padding: 15px;

          .title {
            overflow: hidden;
            font-size: 16px;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .particulars {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .price {
              font-size: 16px;
              color: red;
            }

            .van-button {
              width: 55px;
              height: 32px;
              padding: 0 6px;
              font-size: 12px;
            }
          }
        }
      }
    }
  }

  .van-submit-bar {
    margin-bottom: 50px;
  }
}
</style>